package models

import (
	"fmt"
	"log"

	"github.com/go-redis/redis/v8"

	_ "github.com/lib/pq"
	"xorm.io/xorm"
)

var Engine *xorm.Engine
var RDB *redis.Client

func Init(username string, password string, dbname string, host string, port int, sslmode string, MaxIdleConns int, MaxOpenConns int) *xorm.Engine {
	conStr := fmt.Sprintf("user=%s password=%s dbname=%s host=%s port=%d sslmode=%s", username, password, dbname, host, port, sslmode)
	fmt.Println(conStr)
	engine, err := xorm.NewEngine("postgres", conStr)
	if err != nil {
		log.Fatalln("Xorm New Engine Error:%v", err)
		return nil
	}
	engine.SetMaxIdleConns(MaxIdleConns)
	engine.SetMaxOpenConns(MaxOpenConns)
	err = engine.Ping()
	if err != nil {
		log.Fatalln("Xorm Ping Engine Error:%v", err)
		return nil
	}
	Engine = engine
	return Engine
}

func InitRedis(addr string, password string, defaultDb int) *redis.Client {
	RDB = redis.NewClient(&redis.Options{
		Addr:     addr,
		Password: password,
		DB:       defaultDb,
	})
	return RDB
}
